﻿using Apex.Commons.Extentions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text;

namespace Apex.Commons.Helper
{
    public class RequestHelper
    {
        /// <summary>
        /// 构建动态请求体
        /// </summary>
        /// <param name="parameters">字典</param>
        /// <returns></returns>
        public StringContent BuildBody(Dictionary<string, object> parameters)
        {
            // 将 Dictionary 对象序列化为 JSON 字符串
            var jsonContent = JsonConvert.SerializeObject(parameters);
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
            return content;
        }
        /// <summary>
        /// 构建动态请求体
        /// </summary>
        /// <typeparam name="T">泛型类</typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public StringContent BuildBody<T>(T t) where T : class
        {
            // 创建 HttpContent 对象
            var content = new StringContent(t.ToJsonString(true), Encoding.UTF8, "application/json");
            return content;
        }

        /// <summary>
        /// 解析返回值
        /// </summary>
        /// <returns></returns>
        public async Task<JObject> ParseReturnValueAsync(HttpResponseMessage response)
        {
            // 读取响应内容为字符串
            string responseBody = await response.Content.ReadAsStringAsync();
            // 解析 JSON 内容
            JObject json = JObject.Parse(responseBody);
            return json;
        }
    }
}
